import pygame


class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, direction, speed, owner, damage=1):
        super().__init__()
        self.image = pygame.image.load(f"images/bullet_{direction}.png")
        self.rect = self.image.get_rect(center=(x, y))
        self.direction = direction
        self.speed = speed
        self.owner = owner
        self.damage = damage
        self.active = True

    def move(self):
        if self.direction == "up":
            self.rect.y -= self.speed
        elif self.direction == "down":
            self.rect.y += self.speed
        elif self.direction == "left":
            self.rect.x -= self.speed
        elif self.direction == "right":
            self.rect.x += self.speed

        if self.rect.right < 0 or self.rect.left > 800 or self.rect.bottom < 0 or self.rect.top > 600:
            self.active = False

    def draw(self, screen):
        if self.active:
            screen.blit(self.image, self.rect)

    def update(self, game_map):
        new_rect = self.rect.copy()
        if self.direction == "up":
            new_rect.y -= self.speed
        elif self.direction == "down":
            new_rect.y += self.speed
        elif self.direction == "left":
            new_rect.x -= self.speed
        elif self.direction == "right":
            new_rect.x += self.speed

        if new_rect.right < 0 or new_rect.left > 800 or new_rect.bottom < 0 or new_rect.top > 600:
            self.active = False
        elif game_map.bullet_hit(new_rect):
            self.active = False
        else:
            self.rect = new_rect